﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Web;
using System.Threading.Tasks;
using System.Data;
using Senparc.Weixin.MP.AdvancedAPIs.Media;
using BartonExtension;
using ResponseObject;
using SQLWrapper;
using Model.Weixin;
using Model.Images;
using Model.App;

namespace iShangMai
{
    public class FileUploadController : ApiController
    {
        
        [HttpGet]
        public async Task<ZKResponse> GetWxFile(string mediaId,string token)
        {
            ZKResponse response = await Task.Factory.StartNew<ZKResponse>(() =>
                {
                    ZKResponse resp = new ZKResponse();
                    string url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}".FormatWith(JSSDKAccess.acs_token, mediaId);
                    string pathID = DateTime.Now.ToString("yyyyMMdd");
                    string filePath = HttpRuntime.AppDomainAppPath + "userdata\\imgpool\\{0}".FormatWith(pathID);
                    string filename = IDGenerator.GenerateID().ToString() + ".jpg";
                    if(!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    int downloadRetryCount = 0;
                    bool downloadingFileResult = false;
                    string file = filePath + "\\" + filename;
                    while(downloadRetryCount < 3 && !downloadingFileResult)
                    {
                        System.Threading.Thread.Sleep(1000);
                        downloadingFileResult = HttpDownloader.Get(url, file);
                    }
                    if(downloadingFileResult)
                    {
                        MySQLOperationManager.doSQLOperation(cmd =>
                        {
                            cmd.CommandText = "proc_add_photo_to_pool";
                            cmd.Parameters.Add("?_token", token, ParameterDirection.Input);
                            cmd.Parameters.Add("?_url", "/userdata/imgpool/{0}/{1}".FormatWith(pathID, filename), ParameterDirection.Input);
                            cmd.Parameters.Add("?errorcode", MySql.Data.MySqlClient.MySqlDbType.Int32, ParameterDirection.Output);
                            cmd.Parameters.Add("?imgid", MySql.Data.MySqlClient.MySqlDbType.Int64, ParameterDirection.Output);
                            cmd.ExecuteNonQuery();
                            int errorcode = cmd.Parameters["?errorcode"].Value.toInt32().Value;
                            if (errorcode == -1)
                            {
                                resp.isProcessSuccess = false;
                                resp.errMsg = "Token 验证非法";
                            }
                            else if (errorcode == 0)
                            {
                                Int64 imageID = cmd.Parameters["?imgid"].Value.toInt64().Value;
                                UploadImageEntity entity = this.imageEntityWithFileData(imageID, file, pathID);
                                entity.imageID = imageID;
                                resp.userinfo = entity;
                            }
                        },
                            e =>
                            {
                                if (e != null)
                                {
                                    resp.isProcessSuccess = false;
                                    resp.errMsg = e;
                                }
                            }, CommandType.StoredProcedure, false);
                    }
                    return resp;
                });
            return response;
        }

        public UploadImageEntity imageEntityWithFileData(Int64 imageID, string file,string pathID)
        {
            try
            {
                UploadImageEntity entity = new UploadImageEntity();
                entity.imageID = imageID;
                entity.ori_image_url = "/userdata/imgpool/{0}/{1}".FormatWith(pathID, Path.GetFileName(file));
                var thumbPath = HttpRuntime.AppDomainAppPath + "userdata\\thumbspool\\{0}\\{1}".FormatWith(pathID, entity.imageID);
                if (!Directory.Exists(thumbPath))
                {
                    Directory.CreateDirectory(thumbPath);
                }
                var big_image_path = thumbPath + "\\big_" + Path.GetFileName(file);
                if (ImageHelper.GetFixedRatioImage(file, big_image_path, 750, int.MaxValue))
                {
                    entity.big_thumb_image_url = "/userdata/thumbspool/{0}/{1}".FormatWith(entity.imageID, Path.GetFileName(big_image_path));
                }
                else
                {
                    entity.big_thumb_image_url = "err";
                }

                var medium_image_path = thumbPath + "\\medium_" + Path.GetFileName(file);
                if (ImageHelper.GetFixedRatioImage(file, medium_image_path, 320, int.MaxValue))
                {
                    entity.medium_thumb_image_url = "/userdata/thumbspool/{0}/{1}".FormatWith(entity.imageID, Path.GetFileName(medium_image_path));
                }
                else
                {
                    entity.medium_thumb_image_url = "err";
                }

                var tiny_thumb_path = thumbPath + "\\small_" + Path.GetFileName(file);
                if (ImageHelper.GetFixedRatioImage(file, tiny_thumb_path, 160, int.MaxValue))
                {
                    entity.tiny_thumb_image_url = "/userdata/thumbspool/{0}/{1}".FormatWith(entity.imageID, Path.GetFileName(tiny_thumb_path));
                }
                else
                {
                    entity.tiny_thumb_image_url = "err";
                }
                return entity;
            }
            catch(Exception e)
            {
                return null;
            }
        }
    }
}
